package com.aimo.base.exceptiondemo.core;

import com.aimo.base.exceptiondemo.http.HttpResult;
import com.aimo.base.exceptiondemo.http.HttpStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Author: lmy
 * @Date: 2021/2/19 13:53
 * @Description: 全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 自定义的业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    public HttpResult bizExceptionHandler(BizException e) {
        log.error("发生业务异常！原因是：{}", e.getMessage());
        return HttpResult.error(e.getHttpStatus());
    }

    /**
     * 空指针异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    public HttpResult exceptionHandler(NullPointerException e) {
        log.error("发生空指针异常！原因是:{}", e.getMessage());
        return HttpResult.error(HttpStatus.NULL_POINTER);
    }

    /**
     * 其他异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public HttpResult exceptionHandler(Exception e) {
        log.error("未知异常！原因是:", e);
        return HttpResult.error(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }

    /**
     * 全局参数接收，全局参数绑定（乱入，与全局异常处理无关）
     * @param token
     * @param model
     */
    @ModelAttribute
    public void processParam(@RequestParam("token") String token, Model model) {
        if ("0".equals(token)) {
            throw new BizException(HttpStatus.ERROR_AUTH);
        } else {
            model.addAttribute("userId", "2021");
        }
    }
}
